<?php
class Router
{
	private $path;
	private $args = array();
		
	public function __construct() {}
	
	public function setPath($path) {
		$path = rtrim($path, '/\\').DIRSEP;
		try 
		{	
			if (is_dir($path) == false) {
				throw new Exception('Invalid controller path: `' . $path . '`');
			}
			$this->path = $path;
		}
		catch(Exception $e) {
			die("Error: ".$e->getMessage()." in line ".$e->getLine()." [file: ".$e->getFile()."]");
		}
	}
	
	public function delegate() 
	{
		/* Анализируем путь */
		self::getController($parts);
		$registry = Registry::get("common_vars");
		
		/* Дерево относительно активного раздела */
		$tree_site = self::getTreeSite($registry["structure_id"]);
		Registry::set("tree_site", $tree_site);
		
		/* Контроллер доступен? */
		$file = $this->path."Controller_".ucfirst($registry["controller_file"]);
        if (is_readable($file) == false) {
			$e = new Error404;
        }
		
		/* Разделы где не проверять на наличие субменю */
		Registry::set("NoneLeftMenuSection", array(
			'cars',
			'news'
		));
				
		/* Подключаем файл */
        include_once($file);
		
		/* HEADER */
		Registry::get("smarty")->assign(array(
			'META'        => META,
			'TITLE'       => Registry::get("title"),
			'DESCRIPTION' => Registry::get("description"),
			'KEYWORDS'    => Registry::get("keywords"),
			/* Главное меню :: субменю отключено */
			'MAIN_MENU'   => menu::getMainMenu(false)			
		));
		$View = Registry::get("smarty")->fetch(TEMPLATE_SITE.'header.site.tpl', Registry::get("cache_id"));		
		$View.= $site_module_out;
				
		/* FOOTER */
		Registry::get("smarty")->assign(array(
			'COPYRIGHT' => COPYRIGHT
		));
		$View.= Registry::get("smarty")->fetch(TEMPLATE_SITE.'footer.site.tpl', Registry::get("cache_id"));  
		
		exit($View);           
	}
	
	private function level_url_array(&$parts)
	{
		$route = (empty($_GET['route'])) ? '' : $_GET['route'];		
		$route = trim($route, '/\\');
		$array = explode("/", $route);				
		if(!empty($array)) {
			$i = 0;
			$array_n = array();
			foreach($array as $k=>$v) {
				if(!empty($v)) {
					$i++;
					$array_n[$i] = urlencode($v);
				}
			}			
			if(is_array($array_n)) {				
				foreach($array_n as $k=>$v) {									
					$parts[$k] = "$v";						
				}
			}
		}
		if(empty($parts[1])) {
			$parts[1] = START_PAGE;
		}
	}
	
	private function getController(&$parts)
	{
        /* Получаем раздельные части URL */
        self::level_url_array($parts);		
		
		/* Получаем все данные модуля */
		$r =& Registry::get("MDB")->query("SELECT 
		  ".DB_STRUCTURE.".ID AS structure_id,
		  ".DB_STRUCTURE.".Name AS structure_name,
		  ".DB_STRUCTURE.".Sys_name AS structure_sys_name,
		  ".DB_STRUCTURE.".Parent AS structure_parent_id,
		  ".PRFX."modules.Controller AS controller_file,
		  ".PRFX."templates.Tpl AS controller_template
		FROM
		  ".DB_STRUCTURE."
		  INNER JOIN ".PRFX."modules ON (".DB_STRUCTURE.".Module = ".PRFX."modules.ID)
		  INNER JOIN ".PRFX."templates ON (".DB_STRUCTURE.".Template = ".PRFX."templates.ID)
		WHERE
		  ".DB_STRUCTURE.".Sys_name = '".$parts[1]."' AND 
		  ".DB_STRUCTURE.".Show = '1' 
		LIMIT 1;");
		if (PEAR::isError($r)) {
			die($r->getMessage().' ::: '.$r->getUserInfo());
		}
        if($r->numRows()) {
			Registry::set("common_vars", $r->fetchRow(MDB2_FETCHMODE_ASSOC));
		}
	}
	
	private function getTreeSite($active_id)
	{
		$dependences = array();		
		$r =& Registry::get("MDB")->query("SELECT `ID`,`Parent`,`Name`,`Sys_name`,`Redirect` FROM `".DB_STRUCTURE."` WHERE `ID`='".$active_id."' AND `Show`='1' ORDER BY `Por`");		
		if (PEAR::isError($r)) {
			die($r->getMessage().' ::: '.$r->getUserInfo());
		}		
		while ($p = $r->fetchRow(MDB2_FETCHMODE_ASSOC))
		{
			if($p['parent'] > 0) {
				$dependences[] = $p;				
				$depen         = self::getTreeSite($p['parent']);				
				$dependences   = array_merge_recursive($depen, $dependences);
			}
		}		
		return $dependences;
	}
} 

?>